package com.collections;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by zhuangqi on 2016/11/15.
 */
public class ArrayListRemove {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        list.add("dd");
        list.add("ee");
        list.add("ff");

        //removeErro(list);
        removeTrue(list);
        for (String s:list){
            System.out.println("element:"+s);
        }
    }

    //著名的并发修改异常java.util.ConcurrentModificationException。
    //查看源码原因1：System.arraycopy+1 找不到最后删除的元素
    //导致上面找不到最后删除的元素是因为ArrayList的remove把modCount++;
    private static void removeErro(ArrayList<String> list){
        for (String s:list){
            if (s.equals("bb")){
                list.remove(s);
            }
        }
    }

    private static void removeTrue(ArrayList<String> list){
        Iterator iter = list.iterator();
        while (iter.hasNext()){
            String s = (String) iter.next();
            if (s.equals("bb")){
                iter.remove();
            }
        }
    }
}
